package com.cmbchina.encrypt;

import java.util.Arrays;

/**
 * @author liuxb
 */
public final class PKCS5Padding extends AbstractPadding {
    public PKCS5Padding(int blockSize) {
        super(blockSize);
    }

    public PKCS5Padding(int blockSize, boolean optional) {
        super(blockSize, optional);
    }

    @Override
    public byte[] pad(byte[] input, int offset, int len) {
        if (input == null) {
            throw new IllegalArgumentException("The data to be padding cannot be NULL.");
        } else {
            int length = this.blockSize - len % this.blockSize;
            byte[] padded = new byte[len + length];
            System.arraycopy(input, offset, padded, 0, len);
            Arrays.fill(padded, len, padded.length, (byte) length);
            return padded;
        }
    }

    @Override
    public byte[] unpad(byte[] input, int offset, int len) {
        if (input != null && len > 1) {
            int plen = input[input.length - 1] & 255;
            if (len < plen) {
                throw new IllegalArgumentException(String.format("the size of data [%d] must be more than the size of padding data [%d].", len, plen));
            } else {
                byte[] unpadded = new byte[len - plen];
                System.arraycopy(input, offset, unpadded, 0, len - plen);
                return unpadded;
            }
        } else {
            throw new IllegalArgumentException("the size of data must be more than 1 byte.");
        }
    }

    @Override
    public int outputSize(int len) {
        return len + this.blockSize - len % this.blockSize;
    }
}